import asyncio
import os

import aiohttp
from fake_useragent import UserAgent
"""
地址挂了1
"""
save_directory = 'tsLib'
if not os.path.exists(save_directory):
    os.mkdir(save_directory)

url = "https://v9.dious.cc/20230908/5gr57sIS/2000kb/hls/index.m3u8"
headers = {"User-Agent": UserAgent().random}


async def download_file(session, url, file_path):
    try:
        async with session.get(url) as response:
            if response.status == 200:
                with open(file_path, 'wb') as file:
                    while True:
                        chunk = await response.content.read(1024)
                        if not chunk:
                            break
                        file.write(chunk)
                print(f"下载成功：{url}")
            else:
                print(f"下载失败：{url}")
    except aiohttp.ClientResponseError as e:
        if e.code == 1003:  # Response payload is not completed
            print(f"遇到错误：{str(e)}，正在重新执行请求...")
            await download_file(session, url, file_path)
        else:
            print(f"下载出错：{url}，错误信息：{str(e)}")
    except Exception as e:
        print(f"下载出错：{url}，错误信息：{str(e)}")


async def main():
    async with aiohttp.ClientSession(headers=headers) as session:
        try:
            response = await session.get(url)
            res_list = await response.text()
            lines = res_list.split('\n')
            desired_data = [line for line in lines if line.startswith('/') and line.endswith('.ts')]

            domain = 'https://v9.dious.cc'
            tasks = []
            for item in desired_data:
                download_url = domain + item
                file_path = os.path.join(save_directory, item.split('/')[-1])
                task = asyncio.create_task(download_file(session, download_url, file_path))
                tasks.append(task)

            await asyncio.gather(*tasks)
        except Exception as e:
            print(f"请求出错：{url}，错误信息：{str(e)}")


if __name__ == '__main__':
    asyncio.run(main())
